/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useRef } from 'react';
import { ModalForm, ProFormSelect } from '@ant-design/pro-form';
import { saveBind } from '@/services/jdk/register';
import type { ProFormInstance } from '@ant-design/pro-form';
import { getChainList } from '@/services/jdk/chain';
import { formatOptions } from '../../../utils';
import { message } from 'antd';
import { isFunction } from 'lodash';

interface KbAddModal {
  visible: boolean;
  userId: string;
  successCallBack?: any;
  onCancel: () => void;
}
const KbLssAddModal = ({ visible, userId, successCallBack, onCancel }: KbAddModal) => {
  const formRef = useRef<ProFormInstance>();

  const handleSearch = (value: { keyWords: string }) => {
    const { keyWords } = value;
    return getChainList({ like_name: keyWords }).then((res) => {
      const {
        data: { list = [] },
      } = res;
      return formatOptions(list, 'user_id');
    });
  };

  const onSubmit = async (values: any) => {
    const { code, msg } = await saveBind({ ...values, user_id: userId, type: 'chain' });
    if (code == 0) {
      onCancel();
      if (isFunction(successCallBack)) {
        successCallBack();
      }
      message.success('绑定成功！');
    } else {
      message.error(msg);
    }
  };
  const handleCannel = () => {
    onCancel();
  };

  return (
    <ModalForm
      title='绑定连锁商'
      width={500}
      modalProps={{
        onCancel: handleCannel,
        destroyOnClose: true,
      }}
      formRef={formRef}
      visible={visible}
      onFinish={onSubmit}
    >
      <ProFormSelect
        showSearch
        name='chain_user_id'
        request={handleSearch}
        debounceTime={300}
        fieldProps={{
          placeholder: '请输入连锁商名称搜索',
          style: { width: '100%' },
          defaultActiveFirstOption: false,
          showArrow: false,
          filterOption: false,
        }}
      />
    </ModalForm>
  );
};

export default KbLssAddModal;
